package com.myh.gulimall.authserver.web;

import com.myh.common.exception.BizCodeEnum;
import com.myh.common.utils.R;
import com.myh.gulimall.authserver.service.LoginService;
import com.myh.gulimall.authserver.vo.UserRegistVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: // 类说明，在创建类时要填写
 * @ClassName: LoginController    // 类名，会自动填充
 * @Author: MYH          // 创建者
 * @Date: 2024/5/28 11:22   // 时间
 * @Version: 1.0     // 版本
 */
@Controller
public class LoginController {

    @Autowired
    private LoginService loginService;

    @GetMapping("/login.html")
    public String login() {
        return "login";
    }

    @GetMapping("/reg.html")
    public String reg() {
        return "reg";
    }
    @GetMapping("/testCode.html")
    public String testCode() {
        return "testCode";
    }

    @GetMapping("/sms/sendCode")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phone) {

        Boolean code = loginService.sendCode(phone);
        if (code) {
            return R.ok();
        }else {
            return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMessage());
        }
    }

    @PostMapping("/regist")
    public String regist(@Validated UserRegistVo userRegistVo, BindingResult result, Model model) {

        if (result.hasErrors()){
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(field -> {
                return field.getField();
            }, fieldMessage -> {
                return fieldMessage.getDefaultMessage();
            }));
            model.addAttribute("errors", errors);
            //校验出错，转发到注册页
            return "reg";
        }
        //真正的注册，调用远程服务
        //注册成功，回到登录页
        return "redirect:/login.html";
    }
}
